<template>
  <div>
    <div ref="dragSelect" class="box-container">
      <el-tag
        v-for="(tag, index) in zoneTagList"
        :key="tag.id"
        :class="{ activity: activityindex == index }"
        :disable-transitions="false"
        @click="tagclick(tag, index)"
        @dblclick.native="tagDoublelclick(tag)"
        @close="handleZoneTagDelete(tag)"
      >
        {{ tag.zoneName }}
      </el-tag>
      <el-input
        v-if="inputVisible && authorityHandle(24)"
        ref="saveTagInput"
        v-model="inputValue"
        class="input-new-tag"
        size="small"
        @blur="handleInputBlur"
        @keyup.enter.native="handleInputConfirm"
      />
      <!-- <el-button
        v-if="!inputVisible && authorityHandle(24)"
        class="button-new-tag"
        size="small"
        @click="addNewZone"
      >
        + 添加专区
      </el-button> -->
    </div>
    <div class="table-container">
      <div class="filter-container">
        <k-button
          v-if="authorityHandle(24)"
          class="top-btn"
          value="添加箱子"
          @click.native="addBoxDialog"
        />
        <k-button
          v-if="authorityHandle(24)"
          class="top-btn"
          value="删除箱子"
          @click.native="deleteBox"
        />
        <!-- <k-button class="top-btn" value="玩法介绍" @click.native="ruleGuideDialog" /> -->
        <k-input
          v-model.trim="conditions.keyword"
          class="filter-item"
          is-search
          placeholder="饰品名称或关键词"
          :search-fun="handleFilter"
          @keyup.enter.native="handleFilter"
        />
      </div>

      <!--表格相关 -->
      <el-table
        :data="zoneBoxList"
        fit
        border
        highlight-current-row
        style="width: 100%; border-radius: 8px"
        :header-cell-style="{ background: '#F6F5FA', color: '#4E4F62' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="authorityHandle(24)"
          min-width="60px"
          type="selection"
          align="center"
        />
        <el-table-column
          width="60px"
          type="index"
          label="序号"
          align="center"
        />
        <el-table-column
          prop="boxName"
          min-width="150px"
          label="箱子名称"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="price"
          sortable
          min-width="80px"
          label="箱子价格(R)"
          align="center"
        />

        <el-table-column
          v-if="authorityHandle(24)"
          min-width="100px"
          label="箱子排序"
          align="center"
        >
          <editable-cell
            v-model="row.zoneSort"
            slot-scope="{ row }"
            :show-input="row.editMode"
            @keyup.enter.native="upBoxSort(row)"
          >
            <span
              slot="content"
              style="display: inline-block; width: 100%; height: 100%"
              >{{ row.zoneSort }}</span
            >
          </editable-cell>
        </el-table-column>

        <el-table-column
          v-else
          prop="zoneSort"
          min-width="100px"
          label="箱子排序"
          align="center"
        />

        <el-table-column min-width="150px" label="箱子内饰品" align="center">
          <template slot-scope="scope">
            <div class="cell-baby">
              <span class="ellipsis-span" :title="scope.row.goodsNames">{{
                scope.row.goodsNames
              }}</span>
              <span
                v-show="scope.row.goodsNames"
                class="cp"
                style="color: #3b425d; margin-left: 10px"
                @click="routerToConfig(scope.row.id, 24)"
                >详情</span
              >
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="assembleTime"
          min-width="100px"
          label="添加时间"
          sortable
          align="center"
        />

        <el-table-column min-width="100px" label="上架状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.boxStatus"
              active-color="#3b425d"
              inactive-color="#E9EBF2"
              active-text="上架"
              inactive-text="下架"
              :active-value="1"
              :inactive-value="2"
              :disabled="!authorityHandle(24)"
              @change="boxOnlineState($event, scope)"
            />
          </template>
        </el-table-column>
        <el-table-column min-width="100px" label="箱子状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.hotStatus"
              :disabled="
                authorityHandle(24) && scope.row.boxStatus === 1 ? false : true
              "
              active-color="#3b425d"
              inactive-color="#E9EBF2"
              active-text="热推"
              inactive-text="正常"
              :active-value="1"
              :inactive-value="2"
              @change="boxHostState($event, scope)"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="!authorityHandle(24)"
          width="1px"
          label=""
          align="center"
          style="opacity: 0"
        >
          <template slot-scope="scope">
            <div class="op-div" />
          </template>
        </el-table-column>
      </el-table>
      <!-- 专区修改 updateZone 弹窗 -->
      <k-dialog
        :show-hide.sync="updateZone.showHide"
        :modal-append-to-body="false"
        :append-to-body="true"
        class="addZone-dialog"
        title="修改专区"
        :show-foot="false"
        :two-btn="authorityHandle(24)"
        :close-fun="handleCloseDialog"
        @click="saveZoneData"
      >
        <el-form :model="addZoneInfo" label-width="auto" class="form-modify">
          <el-form-item label="专区名称：" prop="name">
            <el-input
              v-model="addZoneInfo.zoneName"
              :readonly="!authorityHandle(24)"
              placeholder="请输入专区名称"
              disabled
            />
          </el-form-item>
          <el-form-item label="专区图标：" style="display: none">
            <k-upload-file
              ref="upload2"
              v-model="addZoneInfo.zoneImgUrl"
              upload-style="img"
              @successUpload="successUpload"
            />
            <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
          </el-form-item>
          <!-- <el-form-item label="专区开关：">
            <el-switch
              v-model="addZoneInfo.zoneStatus"
              active-color="#3b425d"
              inactive-color="#E9EBF2"
              active-text="开启"
              inactive-text="关闭"
              :active-value="1"
              :inactive-value="2"
              :disabled="!authorityHandle(24)"
              @change="zoneStatusChange($event,addZoneInfo.id)"
            />
          </el-form-item> -->
        </el-form>
      </k-dialog>
      <!-- 添加箱子 弹窗 -->
      <k-dialog
        :show-hide.sync="addBox.showHide"
        :modal-append-to-body="false"
        :append-to-body="true"
        title="添加箱子"
        class="addBox-dialog"
        :two-btn="false"
        :close-fun="addBoxCloseDialog"
      >
        <optionadd
          ref="koptionadd"
          class="search-add"
          title-string="箱子名称"
          multiple
          :result-list="resultList"
          @requestReslutList="requestReslutList"
          @handleCloseDialog="addBoxCloseDialog"
          @saveData="saveZoneBoxData"
        />
      </k-dialog>
      <!-- 玩法介绍 弹窗 -->
      <k-dialog
        :show-hide.sync="ruleGuide.showHide"
        :modal-append-to-body="false"
        :append-to-body="true"
        title="玩法介绍"
        class-name="ruleGuide-dialog"
        :show-foot="false"
        :two-btn="authorityHandle(24)"
        :close-fun="guideClose"
        @click="guideSave"
      >
        <div class="dialog-ruleGuide" style="padding: 30px">
          <el-form :model="ruleGuideContent" label-width="auto">
            <el-form-item label="内容介绍：" prop="content">
              <quill-editor
                ref="myQuillEditor"
                v-model.trim="ruleGuideContent.content"
                :options="editorOption"
                class="editer"
              />
            </el-form-item>
          </el-form>
        </div>
      </k-dialog>
    </div>
  </div>
</template>
<script>
import {
  getZoneList,
  saveZone,
  updateZoneList,
  updateZoneStatus,
  deleteZone,
  getBoxListByZone,
  getFreeBoxList,
  saveBoxToZone,
  updateBoxSortToZone,
  deleteZoneData,
  updateBoxHotStatus,
  updateBoxUpStatus,
  getGeneralDescribe,
  saveGeneralDescribe,
} from "@/api/rules/listdata";
import Optionadd from "@/components/KOptionAdd"; // secondary package based on el-pagination
import Sortable from "sortablejs";
import EditableCell from "@/components/EditableCell";
import { emojiEncode, emojiDecode } from "@/utils/index";

let clickTimer = null;

export default {
  components: { Optionadd, EditableCell },
  data() {
    return {
      activityindex: 0,
      multipleSelection: [],
      editorOption: {
        placeholder: "请输入内容",
        modules: {
          // 富文本初始化
          "emoji-toolbar": true,
          "emoji-shortname": true,
          toolbar: [
            ["bold", "italic", "underline", "strike"], // 加粗，斜体，下划线，删除线
            ["blockquote", "code-block"], // 引用，代码块
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: "ordered" }, { list: "bullet" }], // 列表
            [{ script: "sub" }, { script: "super" }], // 上下标
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ direction: "rtl" }], // 文本方向
            [{ size: ["small", false, "large", "huge"] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ font: [] }], // 字体
            [{ align: [] }], // 对齐方式
            ["clean"], // 清除字体样式
            ["image"], // 上传图片、上传视频
            ["emoji"],
          ],
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false,
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        },
      },
      ruleGuideContent: {
        content: "",
      },
      conditions: {
        keyword: null,
      },
      zoneTagList: [], // 专区列表
      zoneBoxList: [], // 专区下箱子列表
      // 全部数据
      resultList: [
        {
          lineId: -1,
          lineName: " ",
          lineCheck: false,
        },
      ],
      inputVisible: false,
      inputValue: "",
      addZoneInfo: {
        id: undefined,
        zoneName: "",
        zoneSort: "", // 专区排序",
        zoneImgUrl: "", // 专区图标",
        zoneStatus: 2, // 专区开关"
      },
      addBox: {
        showHide: false,
      },
      updateZone: {
        showHide: false,
      },
      ruleGuide: {
        showHide: false,
      },
      currentZoneId: undefined, // 当前的专区id
    };
  },
  mounted() {
    if (this.authorityHandle(24)) {
      this.setSort();
    }
  },
  created() {
    this.loadData(0);
    this.getGeneralDescribe();
  },
  methods: {
    successUpload(data) {
      this.addZoneInfo.zoneImgUrl = data;
    },
    // 搜索查询事件
    handleFilter() {
      this.getBoxListByZone(this.currentZoneId, this.conditions.keyword);
    },
    // 箱子排序
    upBoxSort(row) {
      this.$log(row.zoneSort);
      const obj = { id: row.id, zoneSort: row.zoneSort };
      updateBoxSortToZone(obj).then((res) => {
        if (!res.data.success) {
          this.$message.error(res.data.msg);
        }
        this.$log(res);
      });
    },
    routerToConfig(boxId, permissionid) {
      this.$log(boxId);
      this.$router.push({
        path: "/rootplayrules/config-babylibnew",
        query: { id: boxId, permissionid },
      });
    },
    // 箱子热推
    boxHostState(event, scope) {
      const id = scope.row.id;
      updateBoxHotStatus({ id: id }).then((res) => {
        this.$log(res);
      });
    },
    // 箱子上架
    boxOnlineState(event, scope) {
      const id = scope.row.id;
      updateBoxUpStatus({ id: id }).then((res) => {
        this.$log(res);
      });
    },

    loadData(index) {
      getZoneList().then((res) => {
        this.zoneTagList = [];
        this.zoneTagList = res.data;
        this.$log(this.zoneTagList);
        if (this.zoneTagList.length > 0) {
          this.activityindex = index;
          const zoneId = this.zoneTagList[index].id;
          this.currentZoneId = zoneId;
          this.$log("要获取专区的id " + zoneId + " index:: " + index);
          this.getBoxListByZone(zoneId, "");
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getBoxListByZone(id, key) {
      getBoxListByZone({ id: id, key: key }).then((res) => {
        this.$log(res);
        this.zoneBoxList = [];
        this.zoneBoxList = res.data.map((row) => {
          return {
            ...row,
            editMode: false,
          };
        });
      });
    },
    zoneStatusChange(event, id) {
      this.$log(event);
      updateZoneStatus({ id: id }).then((res) => {
        this.$log(event);
        this.zoneTagList.map((item) => {
          if (item.id === id) item.zoneStatus = event;
        });
      });
    },
    // 修改专区
    saveZoneData() {
      saveZone(this.addZoneInfo).then((res) => {
        if (res.data.success) {
          this.$message.success("保存成功");
          this.$resetForm(this.addZoneInfo);
          this.loadData(this.activityindex);
        } else {
          this.$message.success(res.data.msg);
        }
        this.updateZone.showHide = false;
      });
    },
    // 关闭修改弹窗
    handleCloseDialog() {
      this.$resetForm(this.addZoneInfo);
      this.updateZone.showHide = false;
    },
    // 添加新的专区
    addNewZone() {
      if (this.zoneTagList.length >= 20) {
        this.$message.warning("最多添加 20 个专区");
        return;
      }
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputBlur() {
      this.inputVisible = false;
      this.inputValue = "";
    },
    //  确定添加新的专区保存专区
    handleInputConfirm() {
      const inputValue = this.inputValue;
      this.inputVisible = false;
      this.inputValue = "";
      if (!inputValue) return;
      saveZone({ zoneName: inputValue }).then((res) => {
        if (res.data.success) {
          const id = res.data.data;
          const addZoneInfo = {};
          addZoneInfo.id = id;
          addZoneInfo.zoneName = inputValue;
          this.zoneTagList.push(addZoneInfo);
          this.$log(this.zoneTagList);
        } else {
          this.$message.warning(res.data.msg);
        }
      });
    },
    tagclick(tag, index) {
      clearTimeout(clickTimer);
      clickTimer = setTimeout(() => {
        this.$log("单击：" + index);
        this.currentZoneId = tag.id;
        this.getBoxListByZone(this.currentZoneId, "");
        this.activityindex = index;
      }, 300);
    },
    tagDoublelclick(tag) {
      return;
      clearTimeout(clickTimer);
      this.addZoneInfo.id = tag.id;
      this.addZoneInfo.zoneImgUrl = tag.zoneImgUrl;
      this.addZoneInfo.zoneName = tag.zoneName;
      this.addZoneInfo.zoneStatus = tag.zoneStatus;
      this.updateZone.showHide = true;
    },
    // 删除专区
    handleZoneTagDelete(tag) {
      return;
      this.$log(tag.id);
      if (!tag.id) {
        this.$message.success("删除失败");
        return;
      }
      deleteZone({ id: tag.id }).then((res) => {
        if (res.data.success) {
          this.zoneTagList.splice(this.zoneTagList.indexOf(tag), 1);
          this.$message.success("删除成功");
          this.loadData(this.activityindex);
        } else {
          this.$message.warning(res.data.msg);
        }
      });
    },
    setSort() {
      return;
      const el = this.$refs.dragSelect;
      const _this = this;
      // 设置配置
      const ops = {
        animation: 1000,
        // 拖动结束
        onEnd: function (evt) {
          // _this.$log(evt.oldIndex)
          // _this.$log(evt.newIndex)
          const oldItem = _this.zoneTagList[evt.oldIndex];
          _this.zoneTagList.splice(evt.oldIndex, 1);
          _this.zoneTagList.splice(evt.newIndex, 0, oldItem);
          _this.zoneTagList.map((item, index) => {
            item.zoneSort = index;
          });
          // _this.$log(_this.zoneTagList)
          updateZoneList(_this.zoneTagList).then((res) => {
            _this.$log(_this.activityindex, evt.oldIndex);
            if (evt.oldIndex === _this.activityindex) {
              _this.activityindex = evt.newIndex;
            } else {
              _this.activityindex = evt.oldIndex;
            }
            _this.loadData(_this.activityindex);
          });
        },
      };
      // 初始化
      Sortable.create(el, ops);
    },
    addBoxDialog() {
      this.addBox.showHide = true;
    },
    ruleGuideDialog() {
      this.ruleGuide.showHide = true;
    },
    deleteBox() {
      const _vue = this;
      if (_vue.multipleSelection.length < 1) {
        this.$message.error("请至少选择一条数据进行删除！");
        return;
      }
      const selections = _vue.multipleSelection;
      this.$confirm("确定删除选中的箱子么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var ids = [];
          for (var i = 0; i < selections.length; i++) {
            ids.push(selections[i].id);
          }
          deleteZoneData({ ids: ids }).then((res) => {
            if (res.data.success) {
              this.$message.success("删除成功");
              this.loadData(this.activityindex);
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    handleAvatarSuccess(res, file) {
      this.iconUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    // 请求搜索添加饰品的返回列表
    requestReslutList(value) {
      this.$log(value);
      getFreeBoxList().then((res) => {
        this.resultList = [];
        Object.assign(this.resultList, res.data);
        this.$log(res.data);
      });
    },
    // 保存 数据
    saveZoneBoxData(value) {
      if (value.length < 1) {
        this.$message.error("请选择箱子添加！");
        return;
      }
      saveBoxToZone({ boxIds: value, zoneId: this.currentZoneId }).then(
        (res) => {
          this.$message.success(res.message);
          this.getBoxListByZone(this.currentZoneId, "");
        }
      );
      this.resetZoneBoxDialogData();
      this.addBox.showHide = false;
    },
    // 重置添加箱子数据
    resetZoneBoxDialogData() {
      this.$refs.koptionadd.checkedList = [];
      this.$refs.koptionadd.keyword = "";
    },
    addBoxCloseDialog() {
      this.addBox.showHide = false;
      this.resetZoneBoxDialogData();
    },
    // 保存玩法管理
    guideSave() {
      const contents = emojiEncode(this.ruleGuideContent.content);
      saveGeneralDescribe({ data: contents }).then((res) => {
        this.$log(res);
        this.ruleGuide.showHide = false;
      });
    },
    guideClose() {},
    // 加载玩法管理
    getGeneralDescribe() {
      getGeneralDescribe().then((res) => {
        this.ruleGuideContent.content = emojiDecode(res.data);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
$menuText: #14162e; // 侧边栏字体颜色
$hoverColor: #1d143c; // 鼠标停留主色调浅色
$mainColor: #3b425d; // 主色调

.box-container {
  padding: 20px;
  position: relative;
  height: 135px;
  box-sizing: border-box;
  margin-bottom: 20px;
  background-color: #fdfdfd;
  margin-left: 20px;
  margin-right: 20px;
  margin-top: 40px;
  border-radius: 10px;
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .el-tag {
    color: $mainColor;
    background-color: #ffffff;
    border-color: $mainColor;
    cursor: pointer;
    ::v-deep .el-tag__close {
      color: $mainColor;
    }
    ::v-deep .el-icon-close:hover {
      color: #ffffff;
      background: $mainColor;
    }
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
    &:hover {
      color: #ffffff;
      background: $mainColor;
    }
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  ::v-deep .el-input__inner:focus {
    border-color: $mainColor;
  }
  .activity {
    background-color: $mainColor;
    color: #ffffff;
    ::v-deep .el-tag__close {
      color: #ffffff;
    }
    ::v-deep .el-icon-close:hover {
      color: $mainColor;
      background: #ffffff;
    }
  }
}
.table-container {
  padding: 20px;
  position: relative;
  height: 100%;
  min-height: calc(100vh - 150px);
  box-sizing: border-box;
  margin-bottom: 20px;
  background-color: #fdfdfd;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
}
.filter-container {
  width: 100%;
  height: 48px;
  line-height: 48px;
  margin-bottom: 30px;
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }
  .top-btn {
    font-size: 14px;
    color: #ffffff;
  }
  .kInput {
    position: absolute;
    right: 20px;
  }
}

::v-deep .el-dialog__body {
  padding: 10px 30px;
}
.editer {
  border-radius: 8px;
  float: left;
  box-sizing: border-box;
  color: #606266;
  ::v-deep .ql-container {
    height: 440px;
    border-radius: 0px 0px 8px 8px;
  }
  ::v-deep .ql-toolbar.ql-snow {
    border-radius: 8px 8px 0px 0px;
  }
}

.addZone-dialog {
  ::v-deep .el-dialog__body {
    padding: 10px 80px;
  }

  ::v-deep .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 40px;
  }
}
.upload-btn {
  font-size: 14px;
  color: #ffffff;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.addBox-dialog {
  ::v-deep .el-dialog__body {
    width: 678px;
    text-align: center;
  }
  .search-add {
    margin: 0 auto;
    padding: 50px 0px;
    height: 400px;
  }
}
.cell-baby {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.ellipsis-span {
  width: 100px;
  overflow: hidden;
  display: inline-block;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
